import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './Form';
import * as api from '@/services/deployConfig';
import { PageContainer } from '@ant-design/pro-components';
import * as c from '@/services/consts';

const VpnGroupTreeList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.DeployConfig | undefined>(undefined,);
  const [listType, setListType] = useState<number>(1);

  const actionRef = useRef<ActionType>();
  const { hasRight } = useModel('useAuthModel');

  const { reloadDeployConfigs } = useModel('useGlobalModel', (model) => ({
    reloadDeployConfigs: model.reloadDeployConfigs,
  }));

  // const loadData = async (
  //   params: { [key: string]: any },
  //   sorter?: { [key: string]: any },
  //   filter?: { [key: string]: any },
  // ) => {
  //   const result = await api.list(params, sorter, filter);

  //   //console.log(result);
  //   return Promise.resolve(result);
  // };

  const handleFormSubmit = async (record: API.DeployConfig) => {
    let result: API.Result;
    record.type = listType;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
      await reloadDeployConfigs();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
      await reloadDeployConfigs();
    }
  };

  let columns: ProColumns<API.DeployConfig>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 300,
      sorter: true,
    },
    {
      title: '代码',
      dataIndex: 'action',
      width: 100,
      sorter: true,
    },
    {
      title: '代码类型',
      dataIndex: 'actionType',
      width: 150,
      sorter: true,
      render: (_, record) => {
        return c.getObjectText(c.DeployTypeOptions, record.actionType);
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('deployconfig_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }
        if (hasRight('deployconfig_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={{
          defaultPageSize: 30,
          pageSizeOptions: [
            '30',
            '100',
            '200',
          ],
          hideOnSinglePage: false,
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: listType,
            items: [
              {label: '模板',key: '1'},
              {label: 'SSH Key',key: '2'},
              {label: 'SSH用户',key: '3'},
              {label: 'VpnServer程序包',key: '4'},
              {label: 'Helper程序包',key: '5'},
            ],
            onChange: (tabKey) => {
              setListType(tabKey as number);
            },
          },
        }}
        toolBarRender={() => {
          if (hasRight('deployconfig_create')) {
            return [
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ];
          }
          return [];
        }}
        columns={columns}
        params={{
          type: listType
        }}
        request={api.list}
      />
      <Form
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default VpnGroupTreeList;
